//菜单加载器

//读取/tools中的html
//并对比数据库中的记录

const fs = require('fs')
const Path = require('path')

const windows = global.windows;
const { sqlite, database } = require('../JDBC')

const moduleNames = {}; //记录遍历结果
// const baseDir = Path.join(process.cwd(), "../tools"); //@TODO 打包后
const baseDir = Path.join(process.cwd(), "/tools"); //调试路径

const findIndexHtml = filePath => {
    let htmlPath = Path.join(filePath, "index.html");
    // console.log("check htmlPath",htmlPath);
    if(fs.existsSync(htmlPath)){
        return htmlPath;
    }

    return null;
}

const findIndexcon = filePath => {
    let iconPath = Path.join(filePath, "index.png");
    // console.log("check iconPath",iconPath);
    if(fs.existsSync(iconPath)){
        return iconPath;
    }

    return null;
}


//遍历第一层文件夹名字，以文件名字作为功能名字
//以index.html作为功能页面主页面
const init = () => {
    windows.setInitModule("Loader");

    fs.readdir(baseDir, (e, files) => {
        if(e){
            console.error(e);
            return;
        }
        
        if (!files) {
            return
        }

        files.forEach(filename => {
            // console.log("Loader", filename);
            let filePath = Path.join(baseDir, filename)
            let fileStat = fs.lstatSync(filePath);

            if(!fileStat.isDirectory()){
                return;
            }

            let htmlPath = findIndexHtml(filePath);
            if(!htmlPath){
                return;
            }

            let iconPath = findIndexcon(filePath);
            if(!iconPath){
                iconPath = "";
            }

            moduleNames[filename] = {
                name:filename,
                path: htmlPath,
                icon: iconPath
            }
        })

        updateDatabase();
    })
}

//对比数据库，插入新增功能页面
const updateDatabase = () => {
    sqlite.tableExist("menu").then(exist=>{
        if(!exist){
            let sqlPath = Path.join(__dirname, "default.sql")
            sqlite.doFile(sqlPath)
                .then(updateDatabase) //再次执行
            return
        }
           
        console.log("Loader setting Database");
        // console.log("Loader moduleNames",moduleNames);

        sqlite.menus.queryAll().then(result=>{
            database.serialize(()=>{
                // console.log("Loader begin transaction",result)
                database.run("begin transaction");
                
                const insertSql = `INSERT INTO menu (name,path,icon,solt) values($name,$path,$icon,
                    (SELECT IFNULL(MAX(solt), 0) + 1 FROM menu))`;  //solt字段为最大值+1
                    
                const deleteSql = "delete from menu where name = $name";

                //删除表中存在，但moduleNames中不存在的记录
                if(result){
                    result.forEach(r=>{
                        if(!moduleNames[r.name]){
                            //删掉该记录
                            // console.log("Loader delete one",r)
                            database.run(deleteSql,{
                                $name: r.name
                            });
                            return;
                        }
                    })

                    result = result.map(r=>r.name);
                }

                //moduleNames中的记录更新到数据库
                Object.keys(moduleNames).forEach(key=>{

                    //如果数据库中存在则跳过
                    if(result.indexOf(key) != -1){
                        return;
                    }

                    //新增页面插入数据库
                    let m = moduleNames[key];
                    // console.log("Loader will update on",m)
                    database.run(insertSql,{
                        $name: m.name,
                        $path: m.path,
                        $icon: m.icon,
                    })
                });

                database.run("commit",(e,d)=>{
                    if(e){
                        console.log(e);
                        return;
                    }
                    // console.log("Loader setDatabase success");
                    windows.setInitModuleSuccess("Loader"); 
                });
            })
        })
    })
}

init();

module.exports = moduleNames;